package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.bean.TradeSkuOrderBean;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.DimUtil;
import com.atguigu.gmall.realtime.util.JdbcUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.sql.Connection;
import java.time.Duration;

/**
 * @Author lzc
 * @Date 2023/1/8 08:26
 */
public class Dws_09_TradeSkuOrderBean extends BaseApp {
    public static void main(String[] args) {
        new Dws_09_TradeSkuOrderBean().init(
            4009,
            2,
            "Dws_09_TradeSkuOrderBean",
            Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        // 1. 先把数据封装到 pojo 中
        SingleOutputStreamOperator<TradeSkuOrderBean> beanStream = parseToPojo(stream);
        
        // 2. 按照详情 id 去重
        SingleOutputStreamOperator<TradeSkuOrderBean> distinctedStream = distinctByOrderDetailId(beanStream);
        // 3. 开窗聚合
        SingleOutputStreamOperator<TradeSkuOrderBean> streamWithoutDims = windowAndAgg(distinctedStream);
        // 4. 补充维度信息
        joinDims(streamWithoutDims);
        
        // 5. 写出到 ClickHouse 中
        
    }
    
    private void joinDims(SingleOutputStreamOperator<TradeSkuOrderBean> streamWithoutDims) {
        /*
        补充维度信息:
            sql 中:
                lookup join
            流:
                每来一条数据, 然后去使用相应的客户端, 去查找维度表
                
        维度表需要:
            sku_info:  sku_id ->  sku_name  spu_id tm_id c3_id
            spu_info:   spu_id->sku_name
            base_trademark: tm_id -> tm_name
            base_category3: c3_id -> c3_name c2_id
            base_category2: c2_id -> c2_name c1_id
            base_category1: c1_id -> c1_name
       
         */
        streamWithoutDims
            .map(new RichMapFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {
                
                private Connection conn;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    conn = JdbcUtil.getPhoenixConnection();
                }
                
                @Override
                public TradeSkuOrderBean map(TradeSkuOrderBean bean) throws Exception {
                    // 1. sku_info
                    JSONObject skuInfo = DimUtil.readDimFromPhoenix(conn, "dim_sku_info", bean.getSkuId());
                    bean.setSkuName(skuInfo.getString("SKU_NAME"));
                    bean.setSpuId(skuInfo.getString("SPU_ID"));
                    bean.setTrademarkId(skuInfo.getString("TM_ID"));
                    bean.setCategory3Id(skuInfo.getString("CATEGORY3_ID"));
                    
                    // 2. spu_info
                    JSONObject spuInfo = DimUtil.readDimFromPhoenix(conn, "dim_spu_info", bean.getSpuId());
                    bean.setSpuName(spuInfo.getString("SPU_NAME"));
                    
                    // 3. tm
                    JSONObject tm = DimUtil.readDimFromPhoenix(conn, "dim_base_trademark", bean.getTrademarkId());
                    bean.setTrademarkName(tm.getString("TM_NAME"));
                    
                    // 4. c3
                    JSONObject c3 = DimUtil.readDimFromPhoenix(conn, "dim_base_category3", bean.getCategory3Id());
                    bean.setCategory3Name(c3.getString("NAME"));
                    bean.setCategory2Id(c3.getString("CATEGORY2_ID"));
                    
                    // 5. c2
                    JSONObject c2 = DimUtil.readDimFromPhoenix(conn, "dim_base_category2", bean.getCategory2Id());
                    bean.setCategory2Name(c2.getString("NAME"));
                    bean.setCategory1Id(c2.getString("CATEGORY1_ID"));
                    
                    // 6. c1
                    JSONObject c1 = DimUtil.readDimFromPhoenix(conn, "dim_base_category1", bean.getCategory1Id());
                    bean.setCategory1Name(c1.getString("NAME"));
                    
                    
                    return bean;
                }
            })
            .print();
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> windowAndAgg(
        SingleOutputStreamOperator<TradeSkuOrderBean> distinctedStream) {
        return distinctedStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeSkuOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
                    .withIdleness(Duration.ofSeconds(60))
            
            )
            .keyBy(TradeSkuOrderBean::getSkuId)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeSkuOrderBean>() {
                    @Override
                    public TradeSkuOrderBean reduce(TradeSkuOrderBean value1,
                                                    TradeSkuOrderBean value2) throws Exception {
                        value1.setOriginalAmount(value1.getOriginalAmount().add(value2.getOriginalAmount()));
                        value1.setActivityAmount(value1.getActivityAmount().add(value2.getActivityAmount()));
                        value1.setCouponAmount(value1.getCouponAmount().add(value2.getCouponAmount()));
                        value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                        return value1;
                    }
                },
                new ProcessWindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<TradeSkuOrderBean> elements,
                                        Collector<TradeSkuOrderBean> out) throws Exception {
                        TradeSkuOrderBean bean = elements.iterator().next();
                        
                        bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));
                        
                        bean.setTs(System.currentTimeMillis());
                        
                        out.collect(bean);
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> distinctByOrderDetailId(
        SingleOutputStreamOperator<TradeSkuOrderBean> beanStream) {
        return beanStream
            .keyBy(TradeSkuOrderBean::getOrderDetailId)
            .process(new KeyedProcessFunction<String, TradeSkuOrderBean, TradeSkuOrderBean>() {
                
                private ValueState<TradeSkuOrderBean> beanState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    beanState = getRuntimeContext().getState(new ValueStateDescriptor<TradeSkuOrderBean>("bean", TradeSkuOrderBean.class));
                }
                
                @Override
                public void processElement(TradeSkuOrderBean currentBean,
                                           Context ctx,
                                           Collector<TradeSkuOrderBean> out) throws Exception {
                    
                    TradeSkuOrderBean lastBean = beanState.value();
                    // 1. 把这个数据发送到下游
                    // 1.1 如果是第一条, 直接发
                    // 1.2 如果不是第一条则需要用新数据,减去状态中的数据
                    if (lastBean == null) {
                        out.collect(currentBean);
                    } else { // 不是第一条
                        // 新值减旧值
                        lastBean.setOriginalAmount(currentBean.getOriginalAmount().subtract(lastBean.getOriginalAmount()));
                        lastBean.setActivityAmount(currentBean.getActivityAmount().subtract(lastBean.getActivityAmount()));
                        lastBean.setCouponAmount(currentBean.getCouponAmount().subtract(lastBean.getCouponAmount()));
                        lastBean.setOrderAmount(currentBean.getOrderAmount().subtract(lastBean.getOrderAmount()));
                        
                        out.collect(lastBean);
                    }
                    
                    // 2. 先把数据存入到状态中
                    beanState.update(currentBean);
                    
                }
            });
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
            .map(new MapFunction<String, TradeSkuOrderBean>() {
                @Override
                public TradeSkuOrderBean map(String value) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    return TradeSkuOrderBean.builder()
                        .orderDetailId(obj.getString("id"))
                        .skuId(obj.getString("sku_id"))
                        .originalAmount(obj.getBigDecimal("split_original_amount"))
                        .orderAmount(obj.getBigDecimal("split_total_amount"))
                        .activityAmount(obj.getBigDecimal("split_activity_amount") == null ? new BigDecimal(0) : obj.getBigDecimal("split_activity_amount"))
                        .couponAmount(obj.getBigDecimal("split_coupon_amount") == null ? new BigDecimal(0) : obj.getBigDecimal("split_coupon_amount"))
                        .ts(obj.getLong("ts") * 1000)
                        .build();
                }
            });
    }
}
/*
交易域SKU粒度下单各窗口

各维度各窗口的原始金额、活动减免金额、优惠券减免金额和订单金额
数据源:
    下单明细表
        商品粒度
    
来源 dwd 层下单明细
detail_id    sku_id   原始金额   订单金额     活动
1              sku_1    200      150        null     时间1
null
1              sku_1    200      150        有值      时间2

对数据进行去重:
    按照详情 id 去重, 保留信息最全的
    
    思路:
        1. 如果需要的数据都在左表, 右表的数据在分析的时候不需要
            只要第一条
                使用状态, 状态是 null,就是第一条
            
        2. 需要的数据也在右表, 应该取最后一条(最后一条最全)
           a: 定时器
                第一条数据进来的时候, 定义一个 5s 出发的定时器
                每来一条数据, 都去比较一下时间, 把时间大的流下来
                等到定时器触发的时候, 留下来的一定是最全的
                
                缺点:
                    实效性有点差, 定时器触发之后,才能扎到最全的那条数据
                    
            b: 抵消法
            detail_id    sku_id   原始金额      订单金额     活动
                1         sku_1    200          150        null     存入到状态中
                1         sku_1    200-200      150-150   有值       存入到状200态中  150
                1         sku_1    200-200      150-150   有值
           
           
           detail_id    sku_id   原始金额      订单金额     活动
                1         sku_1    200          150        null  第1条   存入到状态中
                1          sku_1   -200         -150      null
                1         sku_1    200         150        有值  第 2 条   存入到状态中
                1         sku_1    -200         -150        有值  第 2 条
                1         sku_1    200         150    有值  第 3 条   存入到状态中
                
            
按照 sku_id 分组 keyBy

开窗聚合

补充其他维度信息
    需求按照 spu 聚和
        select .. from t group by spu_name
        
    sku_name  spu  tm c3 c2 c1

写出到 clickhouse 中



 */